package com.tian.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.tian.constant.RabbitMQConstant;
import com.tian.message.UserBalanceDecrMessage;
import com.tian.message.UserBalanceIncrMessage;
import com.tian.service.UserBalanceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * {@code @description:}  扣减用户余额消费者
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-11-25 17:23
 * {@code @version:} 1.0
 */
@RabbitListener(queues = RabbitMQConstant.USER_BALANCE_DECR_QUEUE)
@Component
@Slf4j
public class UserBalanceDecrConsumer {
    @Resource
    private UserBalanceService userBalanceService;

    @RabbitHandler
    public void process(Object data, Channel channel, Message message) throws IOException {
        try {
            log.info("【用户余额用户扣减消费者】接受到的消息：{},消息体为：{}", data, message);
            UserBalanceDecrMessage userBalanceDecrMessage = JSON.parseObject(new String(message.getBody()), UserBalanceDecrMessage.class);
            userBalanceService.decreaseUserBalance(userBalanceDecrMessage);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception exception) {
            log.error("【用户余额用户扣减消费者】消费处理失败，原因是", exception);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
